﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using VMDS.Business.Entities;
using VMDS.Business.Processes;
using VMDS.GUIClient.Helper;
using VMDS.GUIClient.Model;
using VMDS.Settings;

namespace VMDS.GUIClient.ViewModels.Management.OSs
{
    class OsManagementViewModel:BaseViewModel
    {
        private BackgroundWorker _worker;
        public ObservableCollection<OS> OSs { get { return ManagerDataStore.Instance.OSs; } }
        

        private OS _os;
        public OS CurrentOS
        {
            get { return _os; }
            set
            {
                _os = value;OnPropertyChanged(()=>CurrentOS);
                OnPropertyChanged(()=>DeleteRequest);
            }
        }

       
        private string _opmsg;
        public string OperMessage
        {
            get { return _opmsg; }
            set { _opmsg = value; OnPropertyChanged(() => OperMessage); }
        }

        private int _opprg;
        public int OperProgress
        {
            get { return _opprg; }
            set { _opprg = value; OnPropertyChanged(() => OperProgress); }
        }

        private bool _ld=false;
        public bool AddDialog
        {
            get { return _ld; }
            set { _ld = value;OnPropertyChanged(()=>AddDialog); }
        }
        public ICommand AddOsShow
        {
            get
            {
                return new BaseCommand(() => { AddDialog = true; });
            }
        }
        void ReInitDialog()
        {
                NewOsPath = "";
                NewOsName = "";
            OperProgress = 0;
            //AddDialog = true;
            
        }
        public ICommand Cancel
        {
            get
            {
                return new BaseCommand(cancel);
            }
        }

        void deleteOs()
        {
            if (MessageBox.Show("Удалить " + CurrentOS.Name + "?", "", MessageBoxButton.YesNo)==MessageBoxResult.Yes)
            {
                ServiceLocator.MainService.DeleteOS(CurrentOS.Id);
                OSs.Remove(CurrentOS);
            }
        }
        public ICommand DeleteRequest
        {
            get { return new BaseCommand(deleteOs, () => CurrentOS != null); }
        }
       
        void cancel()
        {
           if (t != null)
           {
               t.Abort();
               _worker = null;
           }
           OperMessage = "Отмена...";
            ReInitDialog();
                   
                
            AddDialog = false;
            
        }

        private string _newName;
        public string NewOsName
        {
            get { return _newName; }
            set { _newName = value;
                OnPropertyChanged(() => NewOsName);
                OnPropertyChanged(() => AddOs);
            }
        }

        private string _newPath;
        public string NewOsPath
        {
            get { return _newPath; }
            set
            {
                _newPath = value;
                OnPropertyChanged(() => NewOsPath);
                OnPropertyChanged(() => AddOs);
            }
        }
       

        bool CanAdd()
        {
            bool c1 = String.IsNullOrWhiteSpace(NewOsName);
            string s1 = "";
            if (NewOsName != null) s1 = NewOsName.ToLower();
            if (OSs != null)
            {
                bool c2 = OSs.Any(oS => oS.Name.ToLower() == s1);
                if (c1||c2)
                {
                    OperMessage = "Введите корректное название";
                    return false;
                }
            }

            bool c3= !File.Exists(NewOsPath);
            if (c3)
            {
                OperMessage = "Укажите путь к файлу";
                return false;
            }

            string ext= new FileInfo(NewOsPath).Extension;
            bool c4 = (ext.ToLower() != ".vmx") && (ext.ToLower() != ".zip");
            if (c4)
            {
                OperMessage = "Неверный тип файла";
                return false;
            }
            if (_worker != null)
                if (_worker.IsBusy)
                {
                    return false;
                }
            OperMessage = "";
            return true;
        }

        void addOs()
        {
            _worker=new BackgroundWorker();
            _worker.DoWork += new DoWorkEventHandler(_worker_DoWork);
            _worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_worker_RunWorkerCompleted);
            _worker.RunWorkerAsync();
        }

        void _worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            

        }

       

       
        private Thread t;
        void _worker_DoWork(object sender, DoWorkEventArgs e)
        {
            t = Thread.CurrentThread;
            
            OnPropertyChanged(() => AddOs);
            Deployer d = new Deployer()
                             {
                                 SubDirectory = "OS", 
                                 TargetName = NewOsName,
                                 LocalPath=NewOsPath,
                                 CacheDirectory="d:\\virtual\\cache"
                             };
            d.PropertyChanged += new PropertyChangedEventHandler(d_PropertyChanged);
            d.Start();
            OperMessage = "Регистрация";
            ServiceLocator.MainService.AddOs(NewOsName);
            ManagerDataStore.Instance.LoadData();
            OnPropertyChanged(() => OSs);
            AddDialog = false;
            ReInitDialog();
        }

        void d_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "OperMessage") OperMessage = ((Deployer) sender).OperMessage;
            if (e.PropertyName == "OperProgress") OperProgress= ((Deployer) sender).OperProgress;
        }

        public ICommand AddOs
        {
            get { return new BaseCommand(addOs,CanAdd); }
        }

        public  void ReInit()
        {
            if (_worker != null) if (_worker.IsBusy) return;
            _inst=new OsManagementViewModel();
            ManagerDataStore.Instance.LoadData();

        }
        private static OsManagementViewModel _inst;
        public static OsManagementViewModel Instance { get { return _inst ?? (_inst = new OsManagementViewModel()); }
        }

    }
}
